<template>
  <div id="app">
    <header>
      <h1>2024待办事项</h1>
      <form id="new-task-form" @submit.prevent="handleAdd">
        <input
          type="text"
          v-model="newTask"
          id="new-task-input"
          placeholder="把计划写下来吧?"
        />
        <input
          type="submit"
          id="new-task-submit"
          value="Add Task"
        />
      </form>
    </header>
    <main>
      <section class="task-list">
        <h2>任务列表</h2>
        <div id="tasks">
          <template v-for="(task, index) in tasks" :key="index">
            <div class="task">
              <div class="content">
                <input
                  type="text"
                  class="text"
                  v-model="tasks[index]"  <!-- 直接使用 tasks 数组的元素 -->
                  :disabled="readonly[index]"
                />
              </div>
              <div class="actions">
                <button class="edit" @click="handleEdit(index)">
                  {{ btnName[index] }}
                </button>
                <button class="delete" @click="handleDelete(index)">
                  Delete
                </button>
              </div>
            </div>
          </template>
        </div>
      </section>
    </main>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tasks: [],
      newTask: "",
      btnName: [],
      readonly: [],
    };
  },
  methods: {
    handleAdd() {
      if (this.newTask.trim()) {
        this.tasks.push(this.newTask);
        this.newTask = "";
        this.btnName.push("编辑");
        this.readonly.push(true);
      }
    },
    handleDelete(index) {
      this.tasks.splice(index, 1);
      this.btnName.splice(index, 1);
      this.readonly.splice(index, 1);
    },
    handleEdit(index) {
      if (this.btnName[index] === "编辑") {
        this.btnName[index] = "保存";
        this.readonly[index] = false;
      } else {
        this.btnName[index] = "编辑";
        this.readonly[index] = true;
      }
    },
  },
};
</script>

<style scoped>
/* 这里可以添加当前组件特有的样式规则 */
</style>
